package com.hxut.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "QueryCookieServlet",urlPatterns = "/queryCookieServlet")
public class QueryCookieServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        Cookie[] cookies = req.getCookies();
        Map<String, String> map = new HashMap<>();
        for (Cookie cookie : cookies) {
            //URLDecoder.decode(cookie.getName(),"utf-8");
            //URLDecoder.decode(cookie.getValue(),"utf-8");
            map.put(URLDecoder.decode(cookie.getName(),"utf-8"),URLDecoder.decode(cookie.getValue(),"utf-8"));
        }
        map.forEach((key,value)->{
            System.out.println(key+":"+value);
        });
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
